package demo.thread;


public class AtomicityTest {

    public static class AtomicityRunnable implements Runnable {

        private int count = 100000;

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        @Override
        public void run() {
            for (int j = 0; j < count; j++) {
                // 非原子操作
                index++;
            }
        }
    }

    private static Integer index = 0;

    public static void main(String[] args) throws InterruptedException {
        int numThreads = 2;
        int count = 100000;

        Thread[] threads = new Thread[numThreads];

        for (int j = 0; j < numThreads; j++) {
            AtomicityRunnable runnable = new AtomicityTest.AtomicityRunnable();
            runnable.setCount(count);
            threads[j] = new Thread(runnable, "Thread-" + j);
            threads[j].start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("Final value of index = " + index);
        System.out.println("Expected value = " + (numThreads * count));
    }
}

